package 题目集.高精度;

import org.junit.Test;
import 左哥算法.ch07图.Node;

import java.util.List;

/**
 * 两数之和
 * https://leetcode.cn/problems/add-two-numbers/description/
 */
public class ch01_两数之和 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        /*cur其实是上一次的进位*/
        ListNode p = l1, q = l2, curr = res;
        ListNode pre = res;
        while (p != null && q != null) {
            curr.val += p.val + q.val;
            curr.next = new ListNode(curr.val / 10);
            curr.val %= 10;
            p = p.next;
            q = q.next;
            pre = curr;
            curr = curr.next;
        }
        while (p != null) {
            curr.val += p.val;
            curr.next = new ListNode(curr.val / 10);
            curr.val %= 10;
            p = p.next;
            pre = curr;
            curr = curr.next;
        }
        while (q != null) {
            curr.val += q.val;
            curr.next = new ListNode(curr.val / 10);
            curr.val %= 10;
            q = q.next;
            pre = curr;
            curr = curr.next;
        }
        if (curr.val == 0) {
            pre.next=null;
        }
        return res;
    }

    @Test
    public void test() {
        ListNode l1 = new ListNode(9);
        l1.next = new ListNode(9);
        l1.next.next = new ListNode(1);

        ListNode l2 = new ListNode(1);
//        l2.next = new ListNode(6);
//        l2.next.next = new ListNode(4);

        ListNode listNode = addTwoNumbers(l1, l2);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
